package com.ybkj.daijia.server.service.impl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ybkj.daijia.serverUtils.HttpClientUtil;
import com.ybkj.daijia.serverUtils.RegExpValidatorUtils;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.serverUtils.UseAllDataUtil;
import com.ybkj.daijia.api.util.ErrorConstantV4;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.RandomString;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.config.PassengerApi;
import com.ybkj.daijia.config.SalesApi;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.event.model.MemberRebateEvent;
import com.ybkj.daijia.server.mapper.AreaMapper;
import com.ybkj.daijia.server.mapper.CompanyMapper;
import com.ybkj.daijia.server.mapper.DriverMapper;
import com.ybkj.daijia.server.mapper.MemberLoginRecordMapper;
import com.ybkj.daijia.server.mapper.MemberMapper;
import com.ybkj.daijia.server.mapper.PayRecordMapper;
import com.ybkj.daijia.server.mapper.PhoneSmsRecordMapper;
import com.ybkj.daijia.server.mapper.WxBindMapper;
import com.ybkj.daijia.server.mc.Enterprise;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.mc.PassengerAccount;
import com.ybkj.daijia.server.mc.PassengerAccount.PayType;
import com.ybkj.daijia.server.mc.PassengerAddress;
import com.ybkj.daijia.server.mc.PassengerConcats;
import com.ybkj.daijia.server.mc.PassengerGrade;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.MemberLogin;
import com.ybkj.daijia.server.model.PayRecord;
import com.ybkj.daijia.server.model.PayRecord.PayRecordType;
import com.ybkj.daijia.server.model.PhoneSmsRecord;
import com.ybkj.daijia.server.model.SmsTemplet;
import com.ybkj.daijia.server.model.SmsTemplet.SmsType;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.SmsService;
import com.ybkj.daijia.server.service.SuperviceService;
import com.ybkj.daijia.server.sp.CkbaMessage;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpSession;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

/**
 * @author Shine
 */
@Service
public class DefaultMemberService implements MemberService {

    private static final Logger logger = LoggerFactory.getLogger(DefaultMemberService.class);

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private DriverMapper driverMapper;

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private PayRecordMapper payRecordMapper;


    @Autowired
    private PhoneSmsRecordMapper phoneSmsRecordMapper;

    @Autowired
    private WxBindMapper wxBindMapper;

    @Autowired
    private AreaMapper areaMapper;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private TaskExecutor taskExecutor;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Autowired
    private PassengerApi passengerApi;

    @Autowired
    private SalesApi salesApi;

    @Autowired
    private SmsService smsService;

    @Autowired
    private SuperviceService superviceService;

    @Autowired
    private MemberLoginRecordMapper memberLoginRecordMapper;

    public static void main(String[] args) {
        String str = "Sdad";
        System.out.println();
    }

    /* (non-Javadoc)
     * @see com.ybkj.shop.service.AdminService#queryAll()
     */
    public Page<Passenger> queryAll(Integer type, Long gradeId, Long companyId, String startTime,
        String endTime, String param) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        StringBuilder sb = new StringBuilder();
        sb.append(passengerApi.getPassengerBaseURL() + PassengerApi.QUERY_PASSENGER
            + "?appKey={appKey}&appId={appId}&sign={sign}&page={page}&rows={rows}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", (Pager.getPage() + 1) + "");
        kv.put("rows", Pager.getLimit() + "");
        if (null != type) {
            kv.put("type", String.valueOf(type));
            sb.append("&type={type}");
        }
        if (null != gradeId) {
            kv.put("gradeId", String.valueOf(gradeId));
            sb.append("&gradeId={gradeId}");
        }
        if (principal.isCompanyType()) {
            if (null != companyId) {
                kv.put("companyId", String.valueOf(companyId));
                sb.append("&companyId={companyId}");
            }
        } else {
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            sb.append("&companyId={companyId}");
        }
        if (StringUtils.isNotBlank(startTime)) {
            try {
                kv.put("start",
                    String.valueOf(DateUtils.parseDate(startTime, "yyyy-MM-dd").getTime()));
                sb.append("&start={start}");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotBlank(endTime)) {
            try {
                kv.put("end", String.valueOf(DateUtils.parseDate(endTime, "yyyy-MM-dd").getTime()));
                sb.append("&end={end}");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotBlank(param)) {
            kv.put("param", param);
            sb.append("&param={param}");
        }

        String result = passengerApi.get(sb.toString(), kv, settingUtils.get());

        List<Passenger> content = new ArrayList<Passenger>();
        long total = 0;

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new Gson();
                content = gson.fromJson(ja.toString(), new TypeToken<List<Passenger>>() {
                }.getType());
                for (Passenger passenger : content) {
                    passenger.setAreaDaijia(areaMapper.selectDaijiaByPassenger(passenger.getId()));
                    passenger
                        .setAreaZhuanche(areaMapper.selectZhuancheByPassenger(passenger.getId()));
                    passenger.setAreaPaotui(areaMapper.selectPaotuiByPassenger(passenger.getId()));
                }
            }
        }

        return new PageImpl<Passenger>(content, pageable, total);
    }

    public Page<Passenger> findAll(Integer type, Long gradeId, Long companyId, String startTime,
        String endTime, String param) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        StringBuilder sb = new StringBuilder();
        sb.append(passengerApi.getPassengerBaseURL() + PassengerApi.QUERY_PASSENGER
            + "?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();

        if (null != type) {
            kv.put("type", String.valueOf(type));
            sb.append("&type={type}");
        }
        if (null != gradeId) {
            kv.put("gradeId", String.valueOf(gradeId));
            sb.append("&gradeId={gradeId}");
        }
        if (principal.isCompanyType()) {
            if (null != companyId) {
                kv.put("companyId", String.valueOf(companyId));
                sb.append("&companyId={companyId}");
            }
        } else {
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            sb.append("&companyId={companyId}");
        }
        if (StringUtils.isNotBlank(startTime)) {
            try {
                kv.put("start",
                    String.valueOf(DateUtils.parseDate(startTime, "yyyy-MM-dd").getTime()));
                sb.append("&start={start}");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotBlank(endTime)) {
            try {
                kv.put("end", String.valueOf(DateUtils.parseDate(endTime, "yyyy-MM-dd").getTime()));
                sb.append("&end={end}");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotBlank(param)) {
            kv.put("param", param);
            sb.append("&param={param}");
        }

        String result = passengerApi.get(sb.toString(), kv, settingUtils.get());

        List<Passenger> content = new ArrayList<Passenger>();
        long total = 0;

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new Gson();
                content = gson.fromJson(ja.toString(), new TypeToken<List<Passenger>>() {
                }.getType());
                for (Passenger passenger : content) {
                    passenger.setAreaDaijia(areaMapper.selectDaijiaByPassenger(passenger.getId()));
                    passenger
                        .setAreaZhuanche(areaMapper.selectZhuancheByPassenger(passenger.getId()));
                    passenger.setAreaPaotui(areaMapper.selectPaotuiByPassenger(passenger.getId()));
                }
            }
        }

        return new PageImpl<Passenger>(content, pageable, total);
    }

    public Page<Passenger> queryAll(Integer type, Long gradeId, Long companyId, String startTime,
        String endTime) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        StringBuilder sb = new StringBuilder();
        sb.append(passengerApi.getPassengerBaseURL() + PassengerApi.QUERY_PASSENGER
            + "?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();

        if (null != type) {
            kv.put("type", String.valueOf(type));
            sb.append("&type={type}");
        }
        if (null != gradeId) {
            kv.put("gradeId", String.valueOf(gradeId));
            sb.append("&gradeId={gradeId}");
        }
        if (principal.isCompanyType()) {
            if (null != companyId) {
                kv.put("companyId", String.valueOf(companyId));
                sb.append("&companyId={companyId}");
            }
        } else {
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            sb.append("&companyId={companyId}");
        }
        if (StringUtils.isNotBlank(startTime)) {
            try {
                kv.put("start",
                    String.valueOf(DateUtils.parseDate(startTime, "yyyy-MM-dd").getTime()));
                sb.append("&start={start}");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotBlank(endTime)) {
            try {
                kv.put("end", String.valueOf(DateUtils.parseDate(endTime, "yyyy-MM-dd").getTime()));
                sb.append("&end={end}");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        String result = passengerApi.get(sb.toString(), kv, settingUtils.get());

        List<Passenger> content = new ArrayList<Passenger>();
        long total = 0;

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new Gson();
                content = gson.fromJson(ja.toString(), new TypeToken<List<Passenger>>() {
                }.getType());
                for (Passenger passenger : content) {
                    passenger.setAreaDaijia(areaMapper.selectDaijiaByPassenger(passenger.getId()));
                    passenger
                        .setAreaZhuanche(areaMapper.selectZhuancheByPassenger(passenger.getId()));
                    passenger.setAreaPaotui(areaMapper.selectPaotuiByPassenger(passenger.getId()));
                }
            }
        }

        return new PageImpl<Passenger>(content, pageable, total);
    }

    @Override
    public Page<Enterprise> queryAllEnterprise(Long gradeId, Long companyId, String startTime,
        String endTime, String param) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        StringBuilder sb = new StringBuilder();
        sb.append(passengerApi.getPassengerBaseURL() + PassengerApi.QUERY_ENTERPRISE
            + "?appKey={appKey}&appId={appId}&sign={sign}&page={page}&rows={rows}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));
        if (null != gradeId) {
            kv.put("gradeId", String.valueOf(gradeId));
            sb.append("&gradeId={gradeId}");
        }
        if (principal.isCompanyType()) {
            if (null != companyId) {
                kv.put("companyId", String.valueOf(companyId));
                sb.append("&companyId={companyId}");
            }
        } else {
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            sb.append("&companyId={companyId}");
        }
        if (null != startTime) {
            try {
                kv.put("start",
                    String.valueOf(DateUtils.parseDate(startTime, "yyyy-MM-dd").getTime()));
                sb.append("&start={start}");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (null != endTime) {
            try {
                kv.put("end", String.valueOf(DateUtils.parseDate(endTime, "yyyy-MM-dd").getTime()));
                sb.append("&end={end}");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotBlank(param)) {
            kv.put("param", param);
            sb.append("&param={param}");
        }

        String result = passengerApi.get(sb.toString(), kv, settingUtils.get());

        List<Enterprise> content = new ArrayList<Enterprise>();
        long total = 0;

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new Gson();
                content = gson.fromJson(ja.toString(), new TypeToken<List<Enterprise>>() {
                }.getType());
                for (Enterprise enterprise : content) {
                    enterprise
                        .setAreaDaijia(areaMapper.selectDaijiaByEnterprise(enterprise.getId()));
                    enterprise
                        .setAreaZhuanche(areaMapper.selectZhuancheByEnterprise(enterprise.getId()));
                }
            }
        }

        return new PageImpl<Enterprise>(content, pageable, total);
    }

    @Override
    public Page<Passenger> queryAllBlack(Long companyId, String param) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        StringBuilder sb = new StringBuilder();
        sb.append(passengerApi.getPassengerBaseURL() + PassengerApi.QUERY_BLACK
            + "?appKey={appKey}&appId={appId}&sign={sign}&page={page}&rows={rows}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));
        if (principal.isCompanyType()) {
            if (null != companyId) {
                kv.put("companyId", String.valueOf(companyId));
                sb.append("&companyId={companyId}");
            }
        } else {
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            sb.append("&companyId={companyId}");
        }
        if (StringUtils.isNotBlank(param)) {
            kv.put("param", param);
            sb.append("&param={param}");
        }

        String result = passengerApi.get(sb.toString(), kv, settingUtils.get());

        List<Passenger> content = new ArrayList<Passenger>();
        long total = 0;

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new Gson();
                content = gson.fromJson(ja.toString(), new TypeToken<List<Passenger>>() {
                }.getType());
                boolean usealldata = false;
                if (currentUser.isPermitted("usealldata")) {
                    usealldata = true;
                }
                for (Passenger passenger : content) {
                    passenger.setPhone(UseAllDataUtil.useAllData(passenger.getPhone()));
                }
            }
        }

        return new PageImpl<Passenger>(content, pageable, total);
    }

    @Override
    public Page<PassengerGrade> listGrades() {

        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        StringBuilder sb = new StringBuilder();
        sb.append(passengerApi.getPassengerBaseURL() + PassengerApi.QUERY_ALL_GRADES
            + "?appKey={appKey}&appId={appId}&sign={sign}}&page={page}&rows={rows}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));
        String result = passengerApi.get(sb.toString(), kv, settingUtils.get());

        List<PassengerGrade> content = new ArrayList<PassengerGrade>();
        long total = 0;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = jo.getJSONArray("rows");
                Gson gson = new Gson();
                content = gson.fromJson(ja.toString(), new TypeToken<List<PassengerGrade>>() {
                }.getType());
            }
        }
        return new PageImpl<PassengerGrade>(content, pageable, total);
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Passenger> createPersonal(Passenger passenger) {

        Result<Passenger> result = passengerApi.createPersonal(passenger, settingUtils.get());

        if (result.isSuccess()) {
            Passenger p = result.getResult();

//    		if(null!=passenger.getAreaDaijiaId()){
//    			areaMapper.addAreaFeeDaijia(p.getId(),passenger.getAreaDaijiaId());
//    		}

        }

        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Passenger> updatePersonal(Passenger passenger) {

        Company company = companyMapper.selectByPrimaryKey(passenger.getCompanyId());
        passenger.setCompanyName(company.getAbbreviation());

        Result<Passenger> result = passengerApi.updatePersonal(passenger, settingUtils.get());

        if (result.isSuccess()) {
//			if(null!=passenger.getAreaDaijiaId()){
//        		areaMapper.deleteAreaFeeDaijia(passenger.getId());
//    			areaMapper.addAreaFeeDaijia(passenger.getId(),passenger.getAreaDaijiaId());
//    		}
//        	else{
//        		areaMapper.deleteAreaFeeDaijia(passenger.getId());
//        	}
        }

        return result;
    }

//	@Transactional(rollbackFor=Exception.class)
//	public Member insertRecord(Member member) {
//
//		memberMapper.insertRecord(member);
//
//		return member;
//	}

//	public Member findOne(Long id) {
//
//		return memberMapper.selectByPrimaryKey(id);
//	}

//	public List<Member> findByIdIn(Long[] ids) {
//
//		return memberMapper.selectByIdIn(ids);
//	}

    @Transactional(rollbackFor = Exception.class)
    public Result<Passenger> updatePassenger(Passenger passenger) {

        Result<Passenger> result = passengerApi.updatePersonal(passenger, settingUtils.get());

        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Passenger> delete(Passenger passenger) {

        Result<Passenger> result = new Result<Passenger>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();
        sb.append(
            passengerApi.getPassengerBaseURL() + PassengerApi.DELETE_PASSENGER + passenger.getId()
                + "?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();

        String resultStr = passengerApi.delete(sb.toString(), kv, settingUtils.get());

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            String message = jo.getString("message");
            result.setMessage(message);
        } else {

            //删除微信绑定信息
            wxBindMapper.deleteByPhone(passenger.getPhone());

            result.setSuccess(true);
        }

        return result;

    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Enterprise> deleteEnterprise(Enterprise enterprise) {

        Result<Enterprise> result = new Result<Enterprise>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();
        sb.append(
            passengerApi.getPassengerBaseURL() + PassengerApi.DELETE_ENTERPRISE + enterprise.getId()
                + "?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();

        String resultStr = passengerApi.delete(sb.toString(), kv, settingUtils.get());

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            String message = jo.getString("message");
            result.setMessage(message);
        } else {
            List<Passenger> plist = enterprise.getPassengers();
            for (Passenger passenger : plist) {
                //删除微信绑定信息
                wxBindMapper.deleteByPhone(passenger.getPhone());
            }
            result.setSuccess(true);
        }

        return result;

    }

    @Override
    public void getCodeV3(final String phone, Double longitude, Double latitude, String acKey) {

        Passenger passenger = passengerApi.findOnePassengerByPhone(phone, settingUtils.get())
            .getResult();

        if (null == passenger || !passenger.isInBlackList()) {//白名单

            Company company = null;

            if (StringUtils.isNotBlank(acKey)) {
                company = companyMapper.selectByAppKey(acKey);
            }

            if (null == company) {
                if (null == passenger) {
                    if (null != longitude && null != latitude) {

                        String city = "";
                        try {
                            city = HttpClientUtil.getCityByLngAndLat(longitude, latitude);
                        } catch (Exception e) {

                        }

                        if (StringUtils.isNotBlank(city)) {
                            List<Company> pipeiCompanys = companyMapper.selectByAreaCityName(city);

                            if (!CollectionUtils.isEmpty(pipeiCompanys)) {

                                List<Company> notMainCompanys = new ArrayList<Company>();
                                Company cityMainCompany = null;

                                for (Company c : pipeiCompanys) {
                                    if (!c.isCompanyType()) {
                                        if (StringUtils.isBlank(c.getAppKey())) {
                                            notMainCompanys.add(c);
                                        }
                                    } else {
                                        cityMainCompany = c;
                                    }
                                }
                                if (!CollectionUtils.isEmpty(notMainCompanys)) {
                                    company = notMainCompanys
                                        .get(new Random().nextInt(notMainCompanys.size()));
                                }

                                if (null == company) {
                                    if (null != cityMainCompany) {
                                        company = cityMainCompany;
                                    }
                                }

                            }
                        }
                    }
                }
            }

            if (null == passenger) {

                String abbreviation = "";
                if (null != company) {
                    abbreviation = company.getAbbreviation();
                } else {
                    company = companyMapper.selectMainCompany();
                    abbreviation = company.getAbbreviation();
                }

                final String abbreviation2 = abbreviation;

                PhoneSmsRecord oldPhoneSmsRecord = phoneSmsRecordMapper.selectByPhone(phone);
                if (null == oldPhoneSmsRecord) {
                    final String code = String.valueOf(RandomString.randomNum(6));
                    oldPhoneSmsRecord = new PhoneSmsRecord();
                    oldPhoneSmsRecord.setExpired(new Date());
                    oldPhoneSmsRecord.setPhone(phone);
                    oldPhoneSmsRecord.setVcode(code);
                    oldPhoneSmsRecord.setCompanyId(company.getId());
                    phoneSmsRecordMapper.insertRecord(oldPhoneSmsRecord);
                } else {
                    if ((System.currentTimeMillis() - oldPhoneSmsRecord.getExpired().getTime())
                        > 1000 * 60 * 30) {
                        final String code = String.valueOf(RandomString.randomNum(6));
                        oldPhoneSmsRecord.setVcode(code);
                        oldPhoneSmsRecord.setExpired(new Date());
                        oldPhoneSmsRecord.setCompanyId(company.getId());
                        phoneSmsRecordMapper.updateByPrimaryKey(oldPhoneSmsRecord);
                    }
                }

                final String code = oldPhoneSmsRecord.getVcode();
                logger.debug("验证码1：" + code);

                Company main = companyMapper.selectMainCompany();
                Setting setting = settingUtils.get();
                if (!main.getId().equals(company.getId()) && setting.isSmsMainCompany()) {
                    company = main;
                }
                final Company finalCompany = company;
                taskExecutor.execute(new Runnable() {
                    public void run() {
                        int ret = -99;
                        try {
                            SmsTemplet templet = smsService
                                .findByAlias(finalCompany.getId(), SmsType.memberCode);
                            if (null != templet && StringUtils.isNotBlank(templet.getContent())
                                && StringUtils.isNotBlank(finalCompany.getSignName())) {
                                ret = smsService.sendSms(phone, "memberCode",
                                    "{\"公司名\":\"" + abbreviation2 + "\",\"验证码\":\"" + code + "\"}",
                                    finalCompany.getId(), 0, finalCompany.getSignName());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        logger.debug("客户接受短信结果：" + ret);
                    }
                });

            } else {

                if (null == company) {
                    company = companyMapper.selectByPrimaryKey(passenger.getCompanyId());
                }

                final String abbreviation = company.getAbbreviation();

                PhoneSmsRecord oldPhoneSmsRecord = phoneSmsRecordMapper.selectByPhone(phone);
                if (null == oldPhoneSmsRecord) {
                    final String code = String.valueOf(RandomString.randomNum(6));

                    PhoneSmsRecord phoneSmsRecord = new PhoneSmsRecord();
                    phoneSmsRecord.setExpired(new Date());
                    phoneSmsRecord.setPhone(phone);
                    phoneSmsRecord.setVcode(code);
                    phoneSmsRecord.setCompanyId(company.getId());
                    phoneSmsRecordMapper.insertRecord(phoneSmsRecord);

                    logger.debug("验证码2：" + code);
                    Company main = companyMapper.selectMainCompany();
                    Setting setting = settingUtils.get();
                    if (!main.getId().equals(company.getId()) && setting.isSmsMainCompany()) {
                        company = main;
                    }
                    final Company finalCompany = company;
                    taskExecutor.execute(new Runnable() {
                        public void run() {
                            int ret = -99;
                            try {
                                SmsTemplet templet = smsService
                                    .findByAlias(finalCompany.getId(), SmsType.memberCode);
                                if (null != templet && StringUtils.isNotBlank(templet.getContent())
                                    && StringUtils.isNotBlank(finalCompany.getSignName())) {
                                    ret = smsService.sendSms(phone, "memberCode",
                                        "{\"公司名\":\"" + abbreviation + "\",\"验证码\":\"" + code
                                            + "\"}", finalCompany.getId(), 0,
                                        finalCompany.getSignName());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            logger.debug("客户接受短信结果：" + ret);
                        }
                    });
                } else {
                    if ((System.currentTimeMillis() - oldPhoneSmsRecord.getExpired().getTime())
                        > 1000 * 60 * 30) {
                        final String code = String.valueOf(RandomString.randomNum(6));
                        oldPhoneSmsRecord.setVcode(code);
                        oldPhoneSmsRecord.setExpired(new Date());
                        oldPhoneSmsRecord.setCompanyId(company.getId());
                        phoneSmsRecordMapper.updateByPrimaryKey(oldPhoneSmsRecord);
                    }

                    final String code = oldPhoneSmsRecord.getVcode();

                    logger.debug("验证码3：" + code);
                    Company main = companyMapper.selectMainCompany();
                    Setting setting = settingUtils.get();
                    if (!main.getId().equals(company.getId()) && setting.isSmsMainCompany()) {
                        company = main;
                    }
                    final Company finalCompany = company;
                    taskExecutor.execute(new Runnable() {
                        public void run() {
                            int ret = -99;
                            try {
                                SmsTemplet templet = smsService
                                    .findByAlias(finalCompany.getId(), SmsType.memberCode);
                                if (null != templet && StringUtils.isNotBlank(templet.getContent())
                                    && StringUtils.isNotBlank(finalCompany.getSignName())) {
                                    ret = smsService.sendSms(phone, "memberCode",
                                        "{\"公司名\":\"" + abbreviation + "\",\"验证码\":\"" + code
                                            + "\"}", finalCompany.getId(), 0,
                                        finalCompany.getSignName());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            logger.debug("客户接受短信结果：" + ret);
                        }
                    });
                }

            }
        }

    }

//	@Override
//	public Member findByIdCard(String idCard) {
//
//		return memberMapper.selectByIdCard(idCard);
//	}

//	@Override
//	public Member findByEmail(String email) {
//
//		return memberMapper.selectByEmail(email);
//	}

    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> login(String phone, String name, Integer gender, Passenger passenger,
        PhoneSmsRecord phoneSmsRecord, String appversion, String introducer, Double longitude,
        Double latitude, String password) {

        //推荐人
        boolean firstIntroducer = false;//第一次

        if (null == passenger) {//新用户
            passenger = new Passenger();
            passenger.setAppVersion(appversion);
            if (StringUtils.isNotBlank(name)) {
                passenger.setName(name);
            }
            passenger.setType(Passenger.TYPE_PASSENGER);
            passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_APP);
            passenger.setAllowOverdraw(Boolean.FALSE);
            passenger.setLongitude(longitude);
            passenger.setLatitude(latitude);
            passenger.setGender(gender);
            passenger.setPhone(phone);
            passenger.setPassword(password);

            Passenger introducerPassenger = null;
            if (StringUtils.isNotBlank(introducer)) {
                Result<Passenger> result_introducer = passengerApi
                    .findOnePassengerByPhone(introducer, settingUtils.get());
                introducerPassenger = result_introducer.getResult();
            }

            if (null != introducerPassenger) {
                firstIntroducer = true;
                passenger.setIntroducer(introducer);
                passenger.setIntroduceType(0);

                Company company = companyMapper
                    .selectByPrimaryKey(introducerPassenger.getCompanyId());
                passenger.setCompanyId(company.getId());
                passenger.setCompanyName(company.getAbbreviation());
            } else {
                Company company = companyMapper.selectByPrimaryKey(phoneSmsRecord.getCompanyId());
                passenger.setCompanyId(company.getId());
                passenger.setCompanyName(company.getAbbreviation());
            }

            Result<Passenger> result = passengerApi.createPersonal(passenger, settingUtils.get());
            if (result.isSuccess()) {
                passenger = result.getResult();
            } else {
                return null;
            }
        } else {
            if (StringUtils.isNotBlank(name) && StringUtils.isBlank(passenger.getName())) {
                passenger.setName(name);
            }
            if (null != gender && null == passenger.getGender()) {
                passenger.setGender(gender);
            }
            passenger.setLatitude(latitude);
            passenger.setLongitude(longitude);
            passenger.setAppVersion(appversion);
            passenger.setPassword(password);
            passengerApi.updatePersonal(passenger, settingUtils.get());

        }

        Setting setting = settingUtils.get();

        BigDecimal couponMoney = salesApi.sumMoneyByPassenger(passenger.getId());

        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("memberId", passenger.getId());
        dataMap.put("memberHead", setting.getWebUrl() + "/upload/member/" + passenger.getPhoto());
        dataMap.put("memberName", passenger.getName());
        dataMap.put("memberGender", passenger.getGender());
        if (passenger.getType() == Passenger.TYPE_PASSENGER) {
            dataMap.put("memberBalance", passenger.getDrawMoney().add(passenger.getNodrawMoney())
                .setScale(2, BigDecimal.ROUND_HALF_UP));
        } else if (passenger.getType() == Passenger.TYPE_ENTERPRISE) {
            Enterprise enterprise = passengerApi
                .findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get()).getResult();
            dataMap.put("memberBalance", enterprise.getDrawMoney().add(enterprise.getNodrawMoney())
                .setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        dataMap.put("memberCoupon", couponMoney);
        dataMap.put("memberType", passenger.getType());
        dataMap.put("memberAccount", phone);
        dataMap.put("memberCarId", passenger.getPlateNumber());
        dataMap.put("memberUsual", passenger.getAddress());
        dataMap.put("memberCanSign", passenger.isAllowOverdraw());
        dataMap.put("memberCompanyId", passenger.getCompanyId());
        dataMap.put("memberCompanyName", passenger.getCompanyName());
        dataMap.put("memberInBlackList", passenger.isInBlackList());
        Result<PassengerConcats> result_concats = passengerApi
            .findPassengerConcats(passenger.getId(), settingUtils.get());
        List<PassengerConcats> list = result_concats.getData();
        PassengerConcats passengerConcats = null;
        if (!CollectionUtils.isEmpty(list)) {
            passengerConcats = list.get(0);
        }
        if (null != passengerConcats) {
            dataMap.put("memberEcn", passengerConcats.getName());
            dataMap.put("memberEcp", passengerConcats.getPhone());
        }

        Integer limitAmounts = 2;
        if (null != passenger.getGrade_id()) {
            PassengerGrade passengerGrade = passengerApi
                .findOneGrade(passenger.getGrade_id(), setting).getResult();
            if (null != passengerGrade) {
                if (null != passengerGrade.getLimitAmounts()) {
                    limitAmounts = passengerGrade.getLimitAmounts();
                }
            }
        }
        dataMap.put("limitAmounts", limitAmounts);

        phoneSmsRecordMapper.deleteByPhone(phone);

        if (firstIntroducer) {
            MemberRebateEvent memberRebateEvent = new MemberRebateEvent(passenger, null, null, 0);
            applicationEventMulticaster.multicastEvent(memberRebateEvent);
        }

        return dataMap;

    }

    @Transactional(rollbackFor = Exception.class)
    public void cashRecharge(PayRecord payRecord, String trade_no) {

        Passenger passenger = passengerApi
            .findOnePassenger(payRecord.getMemberId(), settingUtils.get()).getResult();

        if (null != passenger) {

            PassengerAccount.PayType payType = null;
            String memo = "";

            if (payRecord.getPayRecordType().equals(PayRecordType.alipay)) {
                payType = PassengerAccount.PayType.RECHARGE_TYPE_ALIPAY;
                memo = "支付宝充值，交易号：" + trade_no;
            } else if (payRecord.getPayRecordType().equals(PayRecordType.wx)) {
                payType = PassengerAccount.PayType.RECHARGE_TYPE_WX;
                memo = "微信充值，交易号：" + trade_no;
            } else if (payRecord.getPayRecordType().equals(PayRecordType.unionpay)) {
                payType = PassengerAccount.PayType.RECHARGE_TYPE_UNION;
                memo = "银联充值，交易号：" + trade_no;
            } else if (payRecord.getPayRecordType().equals(PayRecordType.bestpay)) {
                payType = PassengerAccount.PayType.RECHARGE_TYPE_BESTPAY;
                memo = "翼支付充值，交易号：" + trade_no;
            }

            Result<PassengerAccount> result = new Result<PassengerAccount>();

            if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                result = passengerApi
                    .createPassengerAccount(passenger, null, payRecord.getAmount(), payType,
                        PassengerAccount.OPERATING_SYS, memo, null, null, null, trade_no, true,
                        false, settingUtils.get());
            } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                Enterprise enterprise = passengerApi
                    .findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get())
                    .getResult();
                if (null != enterprise) {
                    result = passengerApi
                        .createEnterpriseAccount(enterprise, payRecord.getAmount(), payType,
                            PassengerAccount.OPERATING_SYS, memo, null, null, null, trade_no, true,
                            false, settingUtils.get());
                }
            }

            //交易成功
            if (result.isSuccess()) {
                payRecord.setTreatment(true);
                payRecordMapper.updateByPrimaryKey(payRecord);
            }

        }
    }

    @Override
    public Page<Map<String, Object>> queryByIntroducer(String introducer, Integer introduceType,
        Integer page, Integer limit) {

        Pageable pageable = new PageRequest(page, limit);

        StringBuilder sb = new StringBuilder();
        sb.append(passengerApi.getPassengerBaseURL() + PassengerApi.QUERY_PASSENGER_BY_INTRODUCER
            + "?appKey={appKey}&appId={appId}&sign={sign}&page={page}&rows={rows}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(page));
        kv.put("rows", String.valueOf(limit));

        kv.put("introducer", introducer);
        sb.append("&introducer={introducer}");

        kv.put("introduceType", String.valueOf(introduceType));
        sb.append("&introduceType={introduceType}");

        String result = passengerApi.get(sb.toString(), kv, settingUtils.get());

        List<Passenger> content = new ArrayList<Passenger>();
        long total = 0;

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new Gson();
                content = gson.fromJson(ja.toString(), new TypeToken<List<Passenger>>() {
                }.getType());
            }
        }

        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(content)) {
            for (Passenger passenger : content) {

                Map<String, Object> map = new HashMap<String, Object>();

                map.put("id", passenger.getId());
                map.put("name", passenger.getName());
                map.put("phone", passenger.getPhone());
                map.put("date", passenger.getCreated());

                mapList.add(map);
            }
        }

        return new PageImpl<Map<String, Object>>(mapList, pageable, total);

    }

    @Override
    public List<PassengerGrade> listAllGrades() {
        StringBuilder sb = new StringBuilder();
        sb.append(passengerApi.getPassengerBaseURL() + PassengerApi.QUERY_ALL_GRADES
            + "?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();

        String result = passengerApi.get(sb.toString(), kv, settingUtils.get());

        List<PassengerGrade> content = new ArrayList<PassengerGrade>();

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray ja = jo.getJSONArray("data");
                Gson gson = new Gson();
                content = gson.fromJson(ja.toString(), new TypeToken<List<PassengerGrade>>() {
                }.getType());
            }
        }
        return content;
    }

    @Override
    public Passenger findOnePassenger(Long id) {

        Result<Passenger> result = passengerApi.findOnePassenger(id, settingUtils.get());

        return result.getResult();
    }

    @Override
    public Enterprise findOneEnterprise(Long id) {

        Result<Enterprise> result = passengerApi.findOneEnterprise(id, settingUtils.get());

        return result.getResult();
    }

    @Override
    public Passenger findOnePassengerByPhone(String phone) {
        Result<Passenger> result = passengerApi.findOnePassengerByPhone(phone, settingUtils.get());

        return result.getResult();
    }

    @Override
    public boolean deleteGrade(Long gradeId) {

        return passengerApi.deleteGrade(gradeId, settingUtils.get());

    }

    @Override
    public boolean disposeGrade(Long gradeId) {
        return passengerApi.disposeGrade(gradeId, settingUtils.get());
    }

    @Override
    public Passenger findOnePassengerByEmail(String email) {

        Result<Passenger> result = passengerApi.findOnePassengerByEmail(email, settingUtils.get());

        return result.getResult();
    }

    @Override
    public Passenger findOnePassengerByIdCard(String idcard) {

        Result<Passenger> result = passengerApi.findOnePassengerByEmail(idcard, settingUtils.get());

        return result.getResult();
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<PassengerAccount> money(Passenger passenger, Long introducerId, BigDecimal money,
        String details, String operating, PayType payType, Long orderId, String orderNo,
        Integer orderType, String tradeNo, Boolean updateBlance, Boolean useNoDrawMoney) {

        Result<PassengerAccount> result = passengerApi
            .createPassengerAccount(passenger, introducerId, money, payType, operating, details,
                orderId, orderNo, orderType, tradeNo, updateBlance, useNoDrawMoney,
                settingUtils.get());

        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<PassengerAccount> moneyEnterprise(Enterprise enterprise, BigDecimal money,
        String details, String operating, PayType payType, Long orderId, String orderNo,
        Integer orderType, String tradeNo, Boolean updateBlance, Boolean useNoDrawMoney) {

        Result<PassengerAccount> result = passengerApi
            .createEnterpriseAccount(enterprise, money, payType, operating, details, orderId,
                orderNo, orderType, tradeNo, updateBlance, useNoDrawMoney, settingUtils.get());

        return result;

    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Passenger> black(Passenger passenger) {

        Result<Passenger> result = new Result<Passenger>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();

        String api = PassengerApi.UNBLACK_PASSENGER;
        api = api.replaceAll("\\{passengerId\\}", String.valueOf(passenger.getId()));
        sb.append(passengerApi.getPassengerBaseURL() + api
            + "?appKey={appKey}&appId={appId}&sign={sign}&inBlackList={inBlackList}");
        sb.append("&inBlackList={inBlackList}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("inBlackList", String.valueOf(Boolean.TRUE));

        String resultStr = passengerApi.put(sb.toString(), kv, settingUtils.get());

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            String message = jo.getString("message");
            result.setMessage(message);
        } else {
            result.setSuccess(true);
        }
        //加入黑名单，推送至监管平台
        superviceService.CkblMessage(passenger, "add");

        return result;

    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Passenger> unblack(Passenger passenger) {

        Result<Passenger> result = new Result<Passenger>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();

        String api = PassengerApi.UNBLACK_PASSENGER;
        api = api.replaceAll("\\{passengerId\\}", String.valueOf(passenger.getId()));
        sb.append(passengerApi.getPassengerBaseURL() + api
            + "?appKey={appKey}&appId={appId}&sign={sign}&inBlackList={inBlackList}");
        sb.append("&inBlackList={inBlackList}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("inBlackList", String.valueOf(Boolean.FALSE));

        String resultStr = passengerApi.put(sb.toString(), kv, settingUtils.get());

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            String message = jo.getString("message");
            result.setMessage(message);
        } else {
            result.setSuccess(true);
        }

        return result;

    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Enterprise> createEnterprise(Enterprise enterprise) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        StringBuilder sb = new StringBuilder();
        Map<String, String> kv = new HashMap<String, String>();

        enterprise.setCompanyId(principal.getCompanyId());
        enterprise.setCompanyName(principal.getCompanyAbbreviation());

        Result<Enterprise> result = passengerApi
            .createEnterprise(sb, kv, enterprise, settingUtils.get());

        if (result.isSuccess()) {
//			Enterprise e=result.getResult();
//			if(null!=enterprise.getAreaDaijiaId()){
//    			areaMapper.addEnterpriseAreaFeeDaijia(e.getId(),enterprise.getAreaDaijiaId());
//    		}
        }

        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Enterprise> updateEnterprise(Enterprise enterprise) {

        Company company = companyMapper.selectByPrimaryKey(enterprise.getCompanyId());
        enterprise.setCompanyName(company.getAbbreviation());

        Result<Enterprise> result = passengerApi.updateEnterprise(enterprise, settingUtils.get());

//		if(result.isSuccess()){
//			if(null!=enterprise.getAreaDaijiaId()){
//        		areaMapper.deleteEnterpriseAreaFeeDaijia(enterprise.getId());
//    			areaMapper.addEnterpriseAreaFeeDaijia(enterprise.getId(),enterprise.getAreaDaijiaId());
//    		}
//        	else{
//        		areaMapper.deleteEnterpriseAreaFeeDaijia(enterprise.getId());
//        	}
//        }

        return result;
    }

    @Override
    public String findCid(Long passengerId) {
        return memberMapper.selectCid(passengerId);
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Passenger> bindDevice(Passenger passenger) {

        Result<Passenger> result = new Result<Passenger>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();

        String api = PassengerApi.UPDATE_PASSENGER_DEVICETYPE;
        api = api.replaceAll("\\{passengerId\\}", String.valueOf(passenger.getId()));
        sb.append(passengerApi.getPassengerBaseURL() + api
            + "?appKey={appKey}&appId={appId}&sign={sign}&deviceType={deviceType}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("deviceType", passenger.getDeviceType());

        String resultStr = passengerApi.put(sb.toString(), kv, settingUtils.get());

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            String message = jo.getString("message");
            result.setMessage(message);
        } else {
            String oldCid = memberMapper.selectCid(passenger.getId());
            if (null == oldCid) {
                memberMapper.addCid(passenger.getId(), passenger.getCid());
            } else {
                memberMapper.updateCid(passenger.getId(), passenger.getCid());
            }

            result.setSuccess(true);
        }

        return result;
    }

    @Override
    public PassengerAddress findUsuallyAddress(Long passengerId, Integer type) {

        Result<PassengerAddress> result_address = passengerApi
            .findPassengerToPlace(passengerId, type, settingUtils.get());

        PassengerAddress passengerAddress = result_address.getResult();

        return passengerAddress;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<PassengerAddress> updateUsuallyAddress(Long passengerId, String address,
        Double addressLat, Double addressLng, Integer type) {

        Result<PassengerAddress> result = new Result<PassengerAddress>();
        result.setSuccess(false);

        Result<PassengerAddress> result_address = passengerApi
            .findPassengerToPlace(passengerId, type, settingUtils.get());

        PassengerAddress passengerAddress = result_address.getResult();

        if (null == passengerAddress) {
            result = passengerApi
                .addPassengerToPlace(passengerId, address, addressLat, addressLng, type,
                    settingUtils.get());
        } else {
            result = passengerApi
                .updatePassengerToPlace(passengerId, passengerAddress.getId(), address, addressLat,
                    addressLng, type, settingUtils.get());
        }

        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<PassengerConcats> updateEcnEcp(Passenger passenger, String memberEcn,
        String memberEcp) {
        Result<PassengerConcats> result = new Result<PassengerConcats>();
        result.setSuccess(false);

        Result<PassengerConcats> result_concats = passengerApi
            .findPassengerConcats(passenger.getId(), settingUtils.get());

        List<PassengerConcats> list = result_concats.getData();
        PassengerConcats passengerConcats = null;

        if (!CollectionUtils.isEmpty(list)) {
            passengerConcats = list.get(0);
        }

        if (null == passengerConcats) {
            result = passengerApi
                .addPassengerConcats(passenger, memberEcn, memberEcp, settingUtils.get());
        } else {
            result = passengerApi
                .updatePassengerConcats(passenger, passengerConcats.getId(), memberEcn, memberEcp,
                    settingUtils.get());
        }

        return result;

    }

    @Override
    public List<Passenger> findAllPassengersByPhone(String phone) {

        StringBuilder sb = new StringBuilder();
        sb.append(passengerApi.getPassengerBaseURL() + PassengerApi.QUERY_ALL_PASSENGER_BY_PHONE
            + "?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();

        sb.append("&phone={phone}");
        kv.put("phone", String.valueOf(phone));

        String result = passengerApi.get(sb.toString(), kv, settingUtils.get());

        List<Passenger> content = new ArrayList<Passenger>();

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new Gson();
                content = gson.fromJson(ja.toString(), new TypeToken<List<Passenger>>() {
                }.getType());
            }
        }

        return content;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<PassengerGrade> createGrade(PassengerGrade passengerGrade) {

        Result<PassengerGrade> result = passengerApi
            .createGrade(passengerGrade, settingUtils.get());

        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<PassengerGrade> updateGrade(PassengerGrade passengerGrade) {

        Result<PassengerGrade> result = passengerApi
            .updateGrade(passengerGrade, settingUtils.get());

        return result;
    }

    @Override
    public Page<Passenger> findByMultiCondition(Integer[] type, Long[] grade,
        Long[] companyIds, Boolean[] permission, Integer[] isPlatform, String startTime,
        String endTime, String phone, String name, String carNumber, String introduceName,
        Integer page, Integer rows) {
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        StringBuilder sb = new StringBuilder();
        sb.append(
            passengerApi.getPassengerBaseURL() + PassengerApi.QUERY_PASSENGER_BY_MULTICONDITION
                + "?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();

        if (page != null) {
            kv.put("page", (page + 1) + "");
            sb.append("&page={page}");
        }
        if (rows != null) {
            kv.put("rows", rows + "");
            sb.append("&rows={rows}");
        }

        if (!principal.isCompanyType()) {
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            sb.append("&companyId={companyId}");
        }

        if (null != type && type.length != 0) {
            kv.put("type", Arrays.toString(type).replace("[", "").replace("]", ""));
            sb.append("&type={type}");
        }
        if (null != grade && grade.length != 0) {
            kv.put("gradeId", Arrays.toString(grade).replace("[", "").replace("]", ""));
            sb.append("&gradeId={gradeId}");
        }
        if (null != permission && permission.length != 0) {
            kv.put("permission", Arrays.toString(permission).replace("[", "").replace("]", ""));
            sb.append("&permission={permission}");
        }
        if (null != isPlatform && isPlatform.length != 0) {
            kv.put("isPlatform", Arrays.toString(isPlatform).replace("[", "").replace("]", ""));
            sb.append("&isPlatform={isPlatform}");
        }
        if (null != companyIds && companyIds.length != 0) {
            kv.put("companyIds", Arrays.toString(companyIds).replace("[", "").replace("]", ""));
            sb.append("&companyIds={companyIds}");
        }
        if (StringUtils.isNotBlank(startTime)) {
            try {
                kv.put("start",
                    String.valueOf(DateUtils.parseDate(startTime, "yyyy-MM-dd").getTime()));
                sb.append("&start={start}");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotBlank(endTime)) {
            try {
                kv.put("end", String.valueOf(DateUtils.parseDate(endTime, "yyyy-MM-dd").getTime()));
                sb.append("&end={end}");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotBlank(phone)) {
            kv.put("phone", phone);
            sb.append("&phone={phone}");
        }
        if (StringUtils.isNotBlank(name)) {
            kv.put("name", name);
            sb.append("&name={name}");
        }
        if (StringUtils.isNotBlank(carNumber)) {
            kv.put("carNumber", carNumber);
            sb.append("&carNumber={carNumber}");
        }
        if (StringUtils.isNotBlank(introduceName)) {
            String introducer = "";
            if (!RegExpValidatorUtils.isDigits(introduceName)) {
                List<Driver> drivers = driverMapper
                    .selectDriverList(null, introduceName, null, null, null, null, null, null, null,
                        null, null, null, null, null, null);
                for (int i = 0; i < drivers.size(); i++) {
                    if (i == drivers.size() - 1) {
                        introducer += drivers.get(i).getUsername();
                    } else {
                        introducer += drivers.get(i).getUsername() + ",";
                    }
                }
            } else {
                introducer = introduceName.replaceAll("，", ",");
            }
            kv.put("introducer", introducer);
            sb.append("&introducer={introducer}");
        }

        String result = passengerApi.get(sb.toString(), kv, settingUtils.get());

        List<Passenger> content = new ArrayList<Passenger>();
        long total = 0;

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new Gson();
                content = gson.fromJson(ja.toString(), new TypeToken<List<Passenger>>() {
                }.getType());

                for (Passenger passenger : content) {
                    passenger.setPhone(UseAllDataUtil.useAllData(passenger.getPhone()));
                    passenger.setUpPlatformInfo(settingUtils.get().isUpPlatformInfo());
                }
            }
        }

        return new PageImpl<Passenger>(content, pageable, total);

    }

    @Override
    public Page<Enterprise> queryAllEnterpriseByParams(String name,
        Long[] greade, String address, String companyName,
        String startTime, String endTime) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        StringBuilder sb = new StringBuilder();
        sb.append(passengerApi.getPassengerBaseURL() + PassengerApi.QUERY_ENTERPRISE_PARAMS
            + "?appKey={appKey}&appId={appId}&sign={sign}&page={page}&rows={rows}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));

        if (!principal.isCompanyType()) {
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            sb.append("&companyId={companyId}");
        }

        if (greade != null && greade.length != 0) {
            kv.put("grade",
                String.valueOf(Arrays.toString(greade).replace("[", "").replace("]", "")));
            sb.append("&grade={grade}");
        }
        if (StringUtils.isNotBlank(companyName)) {
            kv.put("companyName", companyName);
            sb.append("&companyName={companyName}");
        }
        if (StringUtils.isNoneBlank(startTime)) {
            try {
                kv.put("start",
                    String.valueOf(DateUtils.parseDate(startTime, "yyyy-MM-dd").getTime()));
                sb.append("&start={start}");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotBlank(endTime)) {
            try {
                kv.put("end", String.valueOf(DateUtils.parseDate(endTime, "yyyy-MM-dd").getTime()));
                sb.append("&end={end}");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotBlank(name)) {
            kv.put("name", name);
            sb.append("&name={name}");
        }
        if (StringUtils.isNotBlank(address)) {
            kv.put("address", address);
            sb.append("&address={address}");
        }

        String result = passengerApi.get(sb.toString(), kv, settingUtils.get());

        List<Enterprise> content = new ArrayList<Enterprise>();
        long total = 0;

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new Gson();
                content = gson.fromJson(ja.toString(), new TypeToken<List<Enterprise>>() {
                }.getType());
            }
        }

        return new PageImpl<Enterprise>(content, pageable, total);

    }

    @Override
    public PassengerGrade findOneGrade(Long id) {
        Result<PassengerGrade> result = passengerApi.findOneGrade(id, settingUtils.get());

        return result.getResult();
    }

    @Override
    public List<PassengerGrade> findByCompany(Long companyId) {
        StringBuilder sb = new StringBuilder();
        sb.append(passengerApi.getPassengerBaseURL() + PassengerApi.FINDBYCOMPANY
            + "?appKey={appKey}&appId={appId}&sign={sign}&companyId={companyId}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("companyId", companyId + "");
        String string = passengerApi.get(sb.toString(), kv, settingUtils.get());
        List<PassengerGrade> data = new ArrayList<PassengerGrade>();
        if (StringUtils.isNotBlank(string)) {
            JSONObject jo = new JSONObject(string);
            if (jo.getInt("code") == 0) {
                Gson gson = new Gson();
                JSONArray ja = jo.getJSONArray("data");
                data = gson.fromJson(ja.toString(), new TypeToken<List<PassengerGrade>>() {
                }.getType());
            }
        }
        return data;
    }

    @Override
    public void changeCompanyAbbreviation(Long companyId, String abbreviation) {
        StringBuilder sb = new StringBuilder();

        String api = PassengerApi.CHANGE_ABBREVIATION;
        sb.append(passengerApi.getPassengerBaseURL() + api
            + "?appKey={appKey}&appId={appId}&sign={sign}&companyId={companyId}&abbreviation={abbreviation}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("companyId", String.valueOf(companyId));
        kv.put("abbreviation", abbreviation);

        passengerApi.put(sb.toString(), kv, settingUtils.get());
    }

    @Override
    public Result<Map<String, Object>> batchCreate(String data) {
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("passengers", data);
        Result<Map<String, Object>> resultData = new Result<>();
        String result = passengerApi
            .post(passengerApi.getPassengerBaseURL() + PassengerApi.BATCHCREATE, kv,
                settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                resultData.setSuccess(true);
                JSONObject data1 = jo.getJSONObject("data");
                Map<String, Object> mv = new HashMap<>();
                mv.put("phoneCount", data1.optLong("phoneCount", 0L));
                mv.put("rows", data1.optLong("rows", 0L));
                resultData.setResult(mv);
            } else {
                resultData.setSuccess(false);
            }
        }
        return resultData;
    }

    /**
     * @param ids
     * @param session
     */
    @Override
    public void checkMember(Long[] ids, final HttpSession session) {
        final Page<Passenger> passengers = this.findByIds(ids, null, null);
        final List<Passenger> content = passengers.getContent();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, Object> info = new HashMap<>();
                info.put("isEnd", false);
                for (Passenger member : content) {
                    if (StringUtils.isBlank(member.getPhone())) {
                        info.put(member.getName(), "客户联系电话不能为空");
                    }
                }
                info.put("isEnd", true);
                session.setAttribute("checkMemberInfo", info);
            }
        }).start();
    }

    public Page<Passenger> findByIds(Long[] ids, Integer page, Integer rows) {
        Pageable pageable = null;

        Map<String, String> kv = new HashMap<>();
        StringBuilder sb = new StringBuilder(
            passengerApi.getPassengerBaseURL() + PassengerApi.FIND_IDS).append("?appKey={appKey}");
        if (ids != null && ids.length > 0) {
            kv.put("ids", StringUtils.join(ids, ","));
            sb.append("&ids={ids}");
        }
        if (page != null && rows != null) {
            kv.put("page", String.valueOf(page + 1));
            sb.append("&page={page}");
            kv.put("rows", String.valueOf(rows));
            sb.append("&rows={rows}");
        }
        List<Passenger> list = new LinkedList<>();
        Long total = 0l;
        String result = passengerApi.get(sb.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new Gson();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Passenger>>() {
                }.getType());
            }
        }
        if (page != null && rows != null) {
            pageable = new PageRequest(page, rows);
        } else {
            pageable = new PageRequest(1, list.size());
        }

        return new PageImpl<Passenger>(list, pageable, total);
    }

    @Override
    public Map<String, Object> uploadMember(Long[] ids) {
        List<Passenger> content = findByIds(ids, null, null).getContent();
        List<CkbaMessage> ckbas = new LinkedList<>();
        Map<String, Object> data = new HashMap<>();
        int num = 0;
        for (Passenger passenger : content) {
            CkbaMessage ckba = new CkbaMessage();
            ckba.setAppKey(passenger.getAppKey());
            ckba.setPassengerTel(passenger.getPhone());
            ckba.setPassengerName(passenger.getName());
            ckba.setIdentityNumber(passenger.getIdcard());
            try {
                ckba.setRegisterDate(
                    new SimpleDateFormat("yyyy-MM-dd").parse(passenger.getCreated()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            ckba.setSex((passenger.getGender() == 0 ? "MALE" : "FEMALE"));
            ckbas.add(ckba);
            superviceService.CkbaMessage(ckba, passenger);
            num++;
        }
        try {
            data.put("success", true);
            data.put("successNum", num);
            data.put("failNum", ckbas.size() - num);
        } catch (Exception e) {
            e.printStackTrace();
            data.put("success", false);
            data.put("message", "失败");
        }

        return data;
    }

    @Override
    public Map<String, Object> getCodeV4(final String phone, Double longitude, Double latitude,
        String acKey) {

        Passenger passenger = passengerApi.findOnePassengerByPhone(phone, settingUtils.get())
            .getResult();
        Map<String, Object> map = new HashMap<String, Object>();

        if (null == passenger || !passenger.isInBlackList()) {// 白名单

            Company company = null;

            if (StringUtils.isNotBlank(acKey)) {
                company = companyMapper.selectByAppKey(acKey);
            }

            if (null == company) {
                if (null == passenger) {
                    if (null != longitude && null != latitude) {

                        String city = "";
                        try {
                            city = HttpClientUtil.getCityByLngAndLat(longitude, latitude);
                        } catch (Exception e) {

                        }

                        if (StringUtils.isNotBlank(city)) {
                            List<Company> pipeiCompanys = companyMapper.selectByAreaCityName(city);

                            if (!CollectionUtils.isEmpty(pipeiCompanys)) {

                                List<Company> notMainCompanys = new ArrayList<Company>();
                                Company cityMainCompany = null;

                                for (Company c : pipeiCompanys) {
                                    if (!c.isCompanyType()) {
                                        if (StringUtils.isBlank(c.getAppKey())) {
                                            notMainCompanys.add(c);
                                        }
                                    } else {
                                        cityMainCompany = c;
                                    }
                                }
                                if (!CollectionUtils.isEmpty(notMainCompanys)) {
                                    company = notMainCompanys
                                        .get(new Random().nextInt(notMainCompanys.size()));
                                }

                                if (null == company) {
                                    if (null != cityMainCompany) {
                                        company = cityMainCompany;
                                    }
                                }

                            }
                        }
                    }
                }
            }

            if (null == passenger) {

                String abbreviation = "";
                if (null != company) {
                    abbreviation = company.getAbbreviation();
                } else {
                    company = companyMapper.selectMainCompany();
                    abbreviation = company.getAbbreviation();
                }

                final String abbreviation2 = abbreviation;

                PhoneSmsRecord oldPhoneSmsRecord = phoneSmsRecordMapper.selectByPhone(phone);
                if (null == oldPhoneSmsRecord) {
                    final String code = String.valueOf(RandomString.randomNum(6));
                    oldPhoneSmsRecord = new PhoneSmsRecord();
                    oldPhoneSmsRecord.setExpired(new Date());
                    oldPhoneSmsRecord.setPhone(phone);
                    oldPhoneSmsRecord.setVcode(code);
                    oldPhoneSmsRecord.setCompanyId(company.getId());
                    phoneSmsRecordMapper.insertRecord(oldPhoneSmsRecord);
                } else {
                    if ((System.currentTimeMillis() - oldPhoneSmsRecord.getExpired().getTime())
                        > 1000 * 60 * 30) {
                        final String code = String.valueOf(RandomString.randomNum(6));
                        oldPhoneSmsRecord.setVcode(code);
                        oldPhoneSmsRecord.setExpired(new Date());
                        oldPhoneSmsRecord.setCompanyId(company.getId());
                        phoneSmsRecordMapper.updateByPrimaryKey(oldPhoneSmsRecord);
                    }
                }

                final String code = oldPhoneSmsRecord.getVcode();
                logger.debug("验证码1：" + code);

                Map<String, Object> memberLoginMethod = memberLoginMethod(phone, code);
                if ((Integer) memberLoginMethod.get("code") != 200) {
                    return memberLoginMethod;
                }

                Company main = companyMapper.selectMainCompany();
                Setting setting = settingUtils.get();
                if (!main.getId().equals(company.getId()) && setting.isSmsMainCompany()) {
                    company = main;
                }
                final Company finalCompany = company;
                taskExecutor.execute(new Runnable() {
                    public void run() {
                        int ret = -99;
                        try {
                            SmsTemplet templet = smsService
                                .findByAlias(finalCompany.getId(), SmsType.memberCode);
                            if (null != templet && StringUtils.isNotBlank(templet.getContent())
                                && StringUtils.isNotBlank(finalCompany.getSignName())) {
                                //ret = smsService.sendSms(phone, "memberCode", "{\"公司名\":\"" + abbreviation2 + "\",\"验证码\":\"" + code + "\"}", finalCompany.getId(), 0, finalCompany.getSignName());
                                //短信发送（改）
                                com.alibaba.fastjson.JSONObject smsParam = new com.alibaba.fastjson.JSONObject();
                                smsParam.put("code", code);
                                ret = smsService.sendSms(phone, templet.getTemplateId(),
                                    smsParam.toJSONString(), finalCompany.getId(), 0,
                                    finalCompany.getSignName());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        logger.debug("客户接受短信结果：" + ret);
                    }
                });

            } else {

                if (null == company) {
                    company = companyMapper.selectByPrimaryKey(passenger.getCompanyId());
                }

                final String abbreviation = company.getAbbreviation();
                //验证码
                PhoneSmsRecord oldPhoneSmsRecord = phoneSmsRecordMapper.selectByPhone(phone);
                if (null == oldPhoneSmsRecord) {
                    final String code = String.valueOf(RandomString.randomNum(6));

                    PhoneSmsRecord phoneSmsRecord = new PhoneSmsRecord();
                    phoneSmsRecord.setExpired(new Date());
                    phoneSmsRecord.setPhone(phone);
                    phoneSmsRecord.setVcode(code);
                    phoneSmsRecord.setCompanyId(company.getId());
                    phoneSmsRecordMapper.insertRecord(phoneSmsRecord);

                    Map<String, Object> memberLoginMethod = memberLoginMethod(phone, code);
                    if ((Integer) memberLoginMethod.get("code") != 200) {
                        return memberLoginMethod;
                    }

                    logger.debug("验证码2：" + code);
                    Company main = companyMapper.selectMainCompany();
                    Setting setting = settingUtils.get();
                    if (!main.getId().equals(company.getId()) && setting.isSmsMainCompany()) {
                        company = main;
                    }
                    final Company finalCompany = company;
                    taskExecutor.execute(new Runnable() {
                        public void run() {
                            int ret = -99;
                            try {
                                SmsTemplet templet = smsService
                                    .findByAlias(finalCompany.getId(), SmsType.memberCode);
                                if (null != templet && StringUtils.isNotBlank(templet.getContent())
                                    && StringUtils.isNotBlank(finalCompany.getSignName())) {
                                    //ret = smsService.sendSms(phone, "memberCode", "{\"公司名\":\"" + abbreviation + "\",\"验证码\":\"" + code + "\"}", finalCompany.getId(), 0, finalCompany.getSignName());
                                    //短信发送（改）
                                    com.alibaba.fastjson.JSONObject smsParam = new com.alibaba.fastjson.JSONObject();
                                    smsParam.put("code", code);
                                    ret = smsService.sendSms(phone, templet.getTemplateId(),
                                        smsParam.toJSONString(), finalCompany.getId(), 0,
                                        finalCompany.getSignName());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            logger.debug("客户接受短信结果：" + ret);
                        }
                    });
                } else {
                    if ((System.currentTimeMillis() - oldPhoneSmsRecord.getExpired().getTime())
                        > 1000 * 60 * 30) {
                        final String code = String.valueOf(RandomString.randomNum(6));
                        oldPhoneSmsRecord.setVcode(code);
                        oldPhoneSmsRecord.setExpired(new Date());
                        oldPhoneSmsRecord.setCompanyId(company.getId());
                        phoneSmsRecordMapper.updateByPrimaryKey(oldPhoneSmsRecord);
                    }

                    final String code = oldPhoneSmsRecord.getVcode();

                    Map<String, Object> memberLoginMethod = memberLoginMethod(phone, code);
                    if ((Integer) memberLoginMethod.get("code") != 200) {
                        return memberLoginMethod;
                    }

                    Company main = companyMapper.selectMainCompany();
                    Setting setting = settingUtils.get();
                    if (!main.getId().equals(company.getId()) && setting.isSmsMainCompany()) {
                        company = main;
                    }
                    final Company finalCompany = company;
                    taskExecutor.execute(new Runnable() {
                        public void run() {
                            int ret = -99;
                            try {
                                SmsTemplet templet = smsService
                                    .findByAlias(finalCompany.getId(), SmsType.memberCode);
                                if (null != templet && StringUtils.isNotBlank(templet.getContent())
                                    && StringUtils.isNotBlank(finalCompany.getSignName())) {
                                    //ret = smsService.sendSms(phone, "memberCode", "{\"公司名\":\"" + abbreviation + "\",\"验证码\":\"" + code + "\"}", finalCompany.getId(), 0, finalCompany.getSignName());
                                    //短信发送（改）
                                    com.alibaba.fastjson.JSONObject smsParam = new com.alibaba.fastjson.JSONObject();
                                    smsParam.put("code", code);
                                    ret = smsService.sendSms(phone, templet.getTemplateId(),
                                        smsParam.toJSONString(), finalCompany.getId(), 0,
                                        finalCompany.getSignName());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            logger.debug("客户接受短信结果：" + ret);
                        }
                    });
                }

            }
        }
        map.put("code", 200);
        return map;
    }

    private Map<String, Object> memberLoginMethod(String phone, String code) {
        Map<String, Object> map = new HashMap<String, Object>();
        // 修改短信验证码发送接口，次数记录与判定，修改客户登录记录
        MemberLogin memberLogin = memberLoginRecordMapper.findLoginRecord(phone);
        if (memberLogin == null) {// 无登录信息
            map.put("code", 500);
            map.put("message", ErrorConstantV4.MEMBER_LOGIN_ERROR.getMessage());
            return map;
        }
        // 获取短信短信的发送时间
        Date smsTime = memberLogin.getSmsTime();
        if (smsTime == null || DateUtils.isSameDay(new Date(), smsTime)) {// 上次短信发送时间是同一天
            // 判断今日短信发送次数
            if (memberLogin.getSmsNumDay() >= MemberLogin.SMS_SEND_LIMIT) {// 当日发送短信条数已达上限
                // 锁定账户，录入锁定备注
                memberLogin.setIsLock(true);
                memberLogin.setLockMemo("当日发送短信条数已达上限");
                memberLoginRecordMapper.updateLoginRecord(memberLogin);

                map.put("code", 500);
                map.put("message", ErrorConstantV4.SMS_SEND_LIMIT.getMessage());
                return map;
            } else {// 未达上限
                // 发送短信，并更新短信发送时间，发送条数，短信验证码
                memberLogin.setSmsTime(new Date());
                memberLogin.setSmsNumDay(memberLogin.getSmsNumDay() + 1);
                memberLogin.setSmsCode(code);
                memberLoginRecordMapper.updateLoginRecord(memberLogin);
            }
        } else {// 不是同一天
            // 清空短信发送次数
            memberLogin.setSmsTime(new Date());
            memberLogin.setSmsNumDay(1);
            memberLogin.setSmsCode(code);
            memberLoginRecordMapper.updateLoginRecord(memberLogin);
        }
        map.put("code", 200);
        return map;
    }

    @Override
    public Map<String, Object> loginV1(String phone, String name, Integer gender,
        Passenger passenger, PhoneSmsRecord phoneSmsRecord, String appversion, String introducer,
        Double longitude, Double latitude, String password) {

        // 推荐人
        boolean firstIntroducer = false;// 第一次

        if (null == passenger) {// 新用户
            passenger = new Passenger();
            passenger.setAppVersion(appversion);
            if (StringUtils.isNotBlank(name)) {
                passenger.setName(name);
            }
            passenger.setType(Passenger.TYPE_PASSENGER);
            passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_APP);
            passenger.setAllowOverdraw(Boolean.FALSE);
            passenger.setLongitude(longitude);
            passenger.setLatitude(latitude);
            passenger.setGender(gender);
            passenger.setPhone(phone);
            passenger.setPassword(password);

            Passenger introducerPassenger = null;
            if (StringUtils.isNotBlank(introducer)) {
                Result<Passenger> result_introducer = passengerApi
                    .findOnePassengerByPhone(introducer, settingUtils.get());
                introducerPassenger = result_introducer.getResult();
            }

            if (null != introducerPassenger) {
                firstIntroducer = true;
                passenger.setIntroducer(introducer);
                passenger.setIntroduceType(0);

                Company company = companyMapper
                    .selectByPrimaryKey(introducerPassenger.getCompanyId());
                passenger.setCompanyId(company.getId());
                passenger.setCompanyName(company.getAbbreviation());
            } else {
                Company company = companyMapper.selectByPrimaryKey(phoneSmsRecord.getCompanyId());
                passenger.setCompanyId(company.getId());
                passenger.setCompanyName(company.getAbbreviation());
            }

            Result<Passenger> result = passengerApi.createPersonal(passenger, settingUtils.get());
            if (result.isSuccess()) {
                passenger = result.getResult();
            } else {
                return null;
            }
        } else {
            if (StringUtils.isNotBlank(name) && StringUtils.isBlank(passenger.getName())) {
                passenger.setName(name);
            }
            if (null != gender && null == passenger.getGender()) {
                passenger.setGender(gender);
            }
            passenger.setLatitude(latitude);
            passenger.setLongitude(longitude);
            passenger.setAppVersion(appversion);
            if (StringUtils.isNotBlank(password)) {
                passenger.setPassword(password);
            }
            passengerApi.updatePersonal(passenger, settingUtils.get());

        }

        Setting setting = settingUtils.get();

        BigDecimal couponMoney = salesApi.sumMoneyByPassenger(passenger.getId());

        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("memberId", passenger.getId());
        dataMap.put("memberHead", setting.getWebUrl() + "/upload/member/" + passenger.getPhoto());
        dataMap.put("memberName", passenger.getName());
        dataMap.put("memberGender", passenger.getGender());
        if (passenger.getType() == Passenger.TYPE_PASSENGER) {
            dataMap.put("memberBalance", passenger.getDrawMoney().add(passenger.getNodrawMoney())
                .setScale(2, BigDecimal.ROUND_HALF_UP));
        } else if (passenger.getType() == Passenger.TYPE_ENTERPRISE) {
            Enterprise enterprise = passengerApi
                .findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get()).getResult();
            dataMap.put("memberBalance", enterprise.getDrawMoney().add(enterprise.getNodrawMoney())
                .setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        dataMap.put("memberCoupon", couponMoney);
        dataMap.put("memberType", passenger.getType());
        dataMap.put("memberAccount", phone);
        dataMap.put("memberCarId", passenger.getPlateNumber());
        dataMap.put("memberUsual", passenger.getAddress());
        dataMap.put("memberCanSign", passenger.isAllowOverdraw());
        dataMap.put("memberCompanyId", passenger.getCompanyId());
        dataMap.put("memberCompanyName", passenger.getCompanyName());
        dataMap.put("memberInBlackList", passenger.isInBlackList());
        Result<PassengerConcats> result_concats = passengerApi
            .findPassengerConcats(passenger.getId(), settingUtils.get());
        List<PassengerConcats> list = result_concats.getData();
        PassengerConcats passengerConcats = null;
        if (!CollectionUtils.isEmpty(list)) {
            passengerConcats = list.get(0);
        }
        if (null != passengerConcats) {
            dataMap.put("memberEcn", passengerConcats.getName());
            dataMap.put("memberEcp", passengerConcats.getPhone());
        }

        Integer limitAmounts = 2;
        if (null != passenger.getGrade_id()) {
            PassengerGrade passengerGrade = passengerApi
                .findOneGrade(passenger.getGrade_id(), setting).getResult();
            if (null != passengerGrade) {
                if (null != passengerGrade.getLimitAmounts()) {
                    limitAmounts = passengerGrade.getLimitAmounts();
                }
            }
        }
        dataMap.put("limitAmounts", limitAmounts);

        phoneSmsRecordMapper.deleteByPhone(phone);

        if (firstIntroducer) {
            MemberRebateEvent memberRebateEvent = new MemberRebateEvent(passenger, null, null, 0);
            applicationEventMulticaster.multicastEvent(memberRebateEvent);
        }

        return dataMap;

    }

}

